const { maindb } = require('../utils/db.js')
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    userId: { type: String, default: '' }, // 用户id，客服和admin用户为空
    userName: { type: String, default: '' }, // 用户名
    password: { type: String, default: '' }, // 密码
    avatar: { type: String, default: '' }, // 头像
    online: { type: Boolean, default: false }, // 是否在线
    onDuty: { type: Boolean, default: false },// 是否开始值班 
    userType: { type: Number, default: 0 }, // 1 买家  2  卖家  3 客服 4 系统-订单助手 5 系统-客服助手 6 系统-超级管理员
    status: { type: Number, default: 0 }, // 0 正常 1 禁用
    createTime: { type: Date, default: Date.now }, // 创建时间
    updateTime: { type: Date, default: Date.now }, // 更新时间
});


const User = maindb.model('User', userSchema);

// 创建用户, 存在更新，不存在创建
const createUser = async (user) => {
    try {
        const userInfo = await User.findOne({ userId: user.userId });
        if (userInfo) {
            // 更新信息时更新时间
            user.updateTime = Date.now();
            const result = await User.updateOne({ userId: user.userId }, { $set: user });
            const cloneResult = JSON.parse(JSON.stringify(result));
            cloneResult._id = userInfo._id.toString();
            return Promise.resolve({
                type: "update",
                result: cloneResult
            });
        } else {
            const result = await User.create(user);
            return Promise.resolve({
                type: "create",
                result: result
            });
        }
    } catch (e) {
        console.log('createUser error', e);
        return Promise.reject(e);
    }
}

// 获取用户信息
const getUserInfo = async (userId) => {
    try {
        const userInfo = await User.findOne({ userId });
        return Promise.resolve(userInfo);
    } catch (e) {
        console.log('getUserInfo error', e);
        return Promise.reject(e);
    }
}

// 创建客服
const createService = async (service) => {
    try {
        // 检查用户名，如果存在不创建
        const userInfo = await User.findOne({ userName: service.userName });
        if (userInfo) {
            return Promise.resolve(userInfo);
        }
        const result = await User.create(service);
        return Promise.resolve(result);
    } catch (e) {
        console.log('createService error', e);
        return Promise.reject(e);
    }
}
// 客服登录检查账号userName密码password
const serviceLogin = async (service) => {
    try {
        const result = await User.findOne(
            { userName: service.userName, password: service.password },
            { password: 0, __v: 0 }
        );
        // 如果成功更新updateTime
        if (result) {
            await User.updateOne({ _id: result._id }, { $set: { updateTime: Date.now() } });
        }
        return Promise.resolve(result);
    } catch (e) {
        console.log('serviceLogin error', e);
        return Promise.reject(e);
    }
}

// 获取客服列表
const getServiceList = async (params) => {
    try {
        const result = await User.find({ ...params, userType: 3 }, { password: 0, __v: 0 });
        return Promise.resolve(result);
    } catch (e) {
        console.log('getServiceList error', e);
        return Promise.reject(e);
    }
}
// 删除客服
const deleteService = async (id) => {
    try {
        const result = await User.deleteOne({ _id: id });
        return Promise.resolve(result);
    } catch (e) {
        console.log('deleteService error', e);
        return Promise.reject(e);
    }
}
// 更新客服
const updateService = async (id, data) => {
    try {
        // 判断一下id是不是一个正常的id
        if (!mongoose.Types.ObjectId.isValid(id)) {
            return Promise.reject({
                message: '异常的id参数类型,id:' + id
            });
        }
        const result = await User.updateOne({ _id: id }, { $set: data });
        return Promise.resolve(result);
    } catch (e) {
        console.log('updateService error', e);
        return Promise.reject(e);
    }
}
// 获取所有买家卖家列表，userType=1和2的用户
const getUserList = async (params) => {
    try {
        const { page = 1, pageSize = 10, ...otherParams } = params;

        // 打印查询条件,方便调试
        console.log('查询条件:', { userType: { $in: [1, 2] }, ...otherParams });

        // 先检查是否有数据
        const hasData = await User.findOne({ userType: { $in: [1, 2] } });
        if (!hasData) {
            console.log('没有找到任何用户数据');
        }

        const result = await User.find(
            { userType: { $in: [1, 2] }, ...otherParams },
            { password: 0, __v: 0 }
        )
            .sort({ updateTime: -1 }) // 按ID倒序
            .skip((page - 1) * pageSize)
            .limit(Number(pageSize));

        // 打印结果数量
        console.log('查询结果数量:', result.length);

        const total = await User.countDocuments({ userType: { $in: [1, 2] }, ...otherParams });

        return Promise.resolve({
            list: result,
            total,
            totalPages: Math.ceil(total / Number(pageSize)),
            currentPage: Number(page)
        });
    } catch (e) {
        console.log('getUserList error', e);
        return Promise.reject(e);
    }
}


module.exports = {
    createUser,
    getUserInfo,
    createService,
    serviceLogin,
    getServiceList,
    deleteService,
    updateService,
    getUserList
}


